package eteam.aps.systemservice.common;

import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;

public class StringToEnumConverterFactory implements ConverterFactory<String, Enum> {
    private static Class<?> getEnumType(Class<?> targetType) {
        Class<?> enumType = targetType;
        while (enumType != null && !enumType.isEnum()) {
            enumType = enumType.getSuperclass();
        }
        return enumType;
    }

    //public class StringToEnumConverterFactory implements ConverterFactory<String, IBaseEnum<Integer>> {
    //@Override
    //public <T extends IBaseEnum<Integer>> Converter<String, T> getConverter(Class<T> targetType) {
    //    return new StringToEnum(getEnumType(targetType));
    //}
    @Override
    public <T extends Enum> Converter<String, T> getConverter(Class<T> targetType) {
        return new StringToEnum(getEnumType(targetType));
    }

    private static class StringToEnum<T extends Enum> implements Converter<String, T> {
        private final Class<T> enumType;

        public StringToEnum(Class<T> enumType) {
            this.enumType = enumType;
        }

        @Override
        public T convert(String source) {
            source = source.trim();
            if (source.isEmpty()) {
                return null;
            }
            try {
                return this.enumType.getEnumConstants()[Integer.parseInt(source)];
            } catch (Exception e) {
                try {
                    return (T) Enum.valueOf(this.enumType, source);
                } catch (Exception ex) {
                    return null;
                }
            }
        }
    }
}